import getpath
import os
import xlrd
import re
import logging
import copy
import myglobal
import config_json
import sample
import openpyxl
import ajl8900
import icap_q
import ncs300
import icp
class MyDb(icp.MyDb):
    def __init__(self,mainw):
        super().__init__(mainw)
        self.doublefmt="%.3f"
        self.origin_column_w=15
    def getdepart(self):
        if self.depart==None:
            self.depart=myglobal.server.getlx_depart("icpms")  
        return self.depart
    def getejff(self):
        if self.ejff==None:
            self.ejff= myglobal.server.getlx_ejff("icpms")        
        return self.ejff

        return "charindex('ICP-MS',ejff)!=0"
        # return "'ICP-MS' in ejff" 
        return ["ICP-MS"] 
    def resetProperties(self,items):
        self.properties = [
            {"ele":None,"delegate":None,'width':30,'attr': "num",'visible':True,  'header': "序号"},
            {"ele":None,"delegate":None,'width':130,'attr': "sampleid",'visible':True,  'header': "id"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "mass",'visible':True,  'header': "质量"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "volume",'visible':True,  'header': "体积"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "xishi",'visible':True,  'header': "稀释倍数"},
            {"ele":None,"delegate":self.editDelegate,'width':80,'attr': "beizhu",'visible':True,  'header': "备注"},
        ]
        v=list(items.keys())
        v.sort()
        logging.info(v)
        for item in v:
            # logging.info([item[0],"CPS" in item[0]])
            if ("Final" in item[0]) or ("CPS" in item[0]) or ("内标" in item[0]):
                one={"hide":True,"ele":item,"delegate":self.m_doubleDeleget,'width':90,'attr': item[0]+"_"+item[1],'visible':False,  'header': item[0]+" "+item[1].replace("."," ")}
            else:
                #item=('Rh.内标', '103.He')
                one={"ele":item,"delegate":self.m_doubleDeleget,'width':90,'attr': item[0]+"_"+item[1],'visible':True,  'header': item[0]+" "+item[1].replace("."," ")}
            self.properties.append(one)        
    def massMulti(self,xs):
        logging.info("==")
        selections = self.mainw.ui.tableView_report.selectionModel()
        list1 = selections.selectedIndexes()
        treated=[]
        for i in range(len(list1)):
            current = list1[i]
            row = current.row()
            if row in treated:
                pass
            else:
                treated.append(row)
                record = self.mainw.model2.getObjectRow(row)
                mass=myglobal.myfloat(record.mass)
                mass=mass*xs
                m="%0.4f" % mass #保留小数点后4位
                m=float(m)
                record.mass=m
                # vol=myglobal.myfloat(record.volume)
                # logging.info([vol,xs])
                # record.volume=vol*xs*10 #mass
                logging.info([row,mass,m])
                # self.model2.submitAll()
                if m>0.06:
                    vol=100
                else:
                    vol=50
                record.volume=vol
    def getDataDays(self, v):
        filename=config_json.setting['database']
        if config_json.setting["sblx"]=="ajl8900":
            (items,data)=ajl8900.getdata(filename)
        elif config_json.setting["sblx"]=="icap_q":
            (items,data)=icap_q.getdata(filename)
        elif config_json.setting["sblx"]=="ncs300":
            (items,data)=ncs300.getdata(filename)
        at = 1
        objs=[]
        for one in data:
            one["items"]=items
        return self.toObjects(data)        
    def output_xlsx(self, filepath):
        n = self.mainw.model2.rowCount()
        if n == 0:
            return
        self.mainw.export_num+=1
        filepath = filepath +"_"+str(self.mainw.export_num)+ ".xlsx"
        # 1. 创建文件对象（指定文件名，模式，编码方式）a模式 为 下次写入在这次的下一行
        wb = openpyxl.Workbook()
        ws = wb.active
        # 3. 构建列表头
        row = ["id", "mass", "volume", "稀释倍数"]
        for f in self.properties:
            if f["visible"] and f.get("ele") != None:
                row.append(f["header"].split(" ")[0])#'Rh.内标 103.He'
        row.append("备注")
        ws.append(row)
        row = ["BC", "", "", ""]
        for f in self.properties:
            if f["visible"] and f.get("ele") != None:
                row.append(f["ele"][1].split(".")[0])#remove mode
        row.append("")
        ws.append(row)
        row = ["XS", "", "", ""]
        for f in self.properties:
            if f["visible"] and f.get("ele") != None:
                row.append(f.get("xishu",""))
        row.append("")
        ws.append(row)
        for row_idx in range(n):
            record = self.mainw.model2.getObjectRow(row_idx)
            sampleid = str(record.sampleid).strip()
            sampleid_up = sampleid.upper()
            if sampleid_up[-3:]=="%CO":
                row = list(["BLK"])
            else:
                sampleid=self.remove_pingxing(sampleid)
                if sampleid=="BLK":
                    sampleid="BLK_"
                row = list([sampleid])
            tmp=record.mass
            if tmp=="":
                row.append("")
            else:
                mass=myglobal.myfloat(tmp)
                mass="%.4f" % mass
                row.append(mass)
            row.append(record.volume)
            row.append(record.xishi)
            for f in self.properties:
                if f["visible"] and f.get("ele") != None:
                    if sampleid_up[-3:]=="%CO":
                        if f["ele"][0] == "As":# replace with blk_si
                            conc = myglobal.myfloat(getattr(record,f["attr"]))
                            if conc<0:
                                conc=""
                            else:
                                conc=self.doublefmt % conc
                        else:
                            conc =""
                        row.append(conc)
                    else:
                        conc = myglobal.myfloat(getattr(record,f["attr"]))
                        conc=self.doublefmt % conc
                        row.append(conc)
            row.append(record.beizhu)
            ws.append(row)
        self.output_append_common(ws)
        for one in self.mainw.appends:
            k=one[0]
            w=one[1]
            l=w.l.text()
            v=w.t.text()
            row = [k+"&" + v,l, "", "", ""]
            ws.append(row)
            config_json.setting["append"]["icpms"][k]=[l,v]
        ws = wb.create_sheet("sheet2")
        hang=self.output_origin(ws)+1
        if config_json.setting["sblx"] =="icap_q":
            icap_q.output_curve(ws,hang)
        wb.save(filepath)
        self.mainw.ui.textEdit.insertPlainText(filepath + "\n")
        scrollbar = self.mainw.ui.textEdit.verticalScrollBar()
        scrollbar.setSliderPosition(scrollbar.maximum()) 
if __name__ == "__main__":
    file = os.path.join(getpath.getpath(),"..","data", "029218-1.xlsx")
    config_json.setting['database'] = file
    db = MyDb(None)
    objs=db.getDataDays(200)
    for obj in objs:
        print(obj.sampleid)
        for one in obj.items.keys():
            print(one[0]+"_"+one[1],getattr(obj,one[0]+"_"+one[1]))
